package com.xyh.transaction.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

public class GoodsCodeGenerator {
    private static final AtomicInteger counter = new AtomicInteger(0);
    private static final int MAX_COUNT = 9999; // 最大值可根据需要调整

    public static synchronized String generateGoodsCode() {
        // 获取当前时间戳部分
        String datePart = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());

        // 获取并递增计数器的值
        int count = counter.getAndIncrement();

        // 当计数器达到最大值后重置
        if (count > MAX_COUNT) {
            counter.set(0);
            count = counter.getAndIncrement();
        }

        // 格式化计数器部分，确保是4位
        String countPart = String.format("%04d", count);

        // 拼接并返回商品代码
        return "G" + datePart + countPart;
    }

    public static void main(String[] args) {
        // 测试生成商品代码
        for (int i = 0; i < 20; i++) {
            System.out.println(generateGoodsCode());
        }
    }
}
